import asyncio
import os.path
import re
from asyncio import StreamReader

import requests
from lxml import etree
# import execise_proxy_ip
import aiohttp
import random
import time

url_index = "https://dandanzan.net"
url_movie_item_1 = "/fetch_plays/"
url_movie_item_2 = "/chao_qing"
url_lib = "https://baidu.sd-play.com/"


# 获取IP数组
# ips = execise_proxy_ip.get_ips()
async def get_index_m3u8_by_chao_qing():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://dandanzan.net/fetch_plays/20232240/chao_qing", ssl=False) as response:
            title_and_id_and_video_plays = {}
            ret = await response.text()
            if response.status != 200:
                return -1
            ret = eval(ret)
            if not os.path.exists("aa"):
                os.makedirs("aa")
            title_and_id_and_video_plays["video_plays"] = ret.get("video_plays")
            return title_and_id_and_video_plays


# 获取视频的index_m3u8接口的返回值
async def get_index_m3u8(play_data):
    play_data = play_data
    async with aiohttp.ClientSession() as session:
        async with session.get(play_data, ssl=False) as response:
            ret = await response.text("utf8")

            m3u8 = re.findall("/\d.*?/\w.*?/\w.*?/\w.*?/index.m3u8", ret, re.S)[0]
            index_m3u8 = url_lib + m3u8
            async with aiohttp.ClientSession() as session:
                async with session.get(index_m3u8, ssl=False) as res:
                    with open("aa/index.m3u8", "wb") as f:
                        f.write(await res.content.read())
                    if res.status != 200:
                        os.remove("aa/index.m3u8")
                        return -1


async def get_key_ts_by_index_m3u8(title_and_id):
    if not os.path.exists("aa/index.m3u8"):
        return -1
    with open("aa/index.m3u8") as f:
        m3u8 = f.read()
    ts_list = re.findall("https:.*?\.ts", m3u8)
    key = re.findall("https:.*?\.key", m3u8)[0]
    key_name = os.path.basename(key)
    async with aiohttp.ClientSession() as session:
        async with session.get(key, ssl=False) as response:
            with open(f"aa/{key_name}", "wb") as f:
                f.write(await response.content.read())
    return ts_list


async def get_ts(ts,ts_name):
    async with aiohttp.ClientSession() as session:
        async with session.get(ts, ssl=False) as response:
            with open(f"aa/{ts_name}", "wb") as f:
                f.write(await response.content.read())
                print(f"{ts_name}写入完成")


async def ts_to_mp4_by_ffmpeg():
    with open("aa/index.m3u8", "r") as f:
        m3u8 = f.read()
    m3u8 = m3u8.replace("https://baidu.shanshanku.com/20221103/wy9vS8N9/1200kb/hls/", "")
    with open("aa/index.m3u8", "w") as f:
        f.write(m3u8)
    print(m3u8)
    os.chdir("aa")
    os.system(
        'ffmpeg -allowed_extensions ALL -protocol_whitelist "file,http,crypto,tcp" -i index.m3u8 -c copy aa.mp4')
    print("aa" + "下载完毕")


async def main():
    # 从index.m3u8中获取电影的m3u8的列表，写到文件中

    title_super_definition_href_list= await get_index_m3u8_by_chao_qing()
    play_data=""
    for video in title_super_definition_href_list["video_plays"]:
        if str(video["src_site"]).startswith("sd"):
            play_data = play_data = video["play_data"]
            break
    tasks_item_2 = await  get_index_m3u8(play_data)
    #
    # 根据文件获取全部的key文件并把ts拿回来
    ts_list_and_name = []
    tasks_item_3 = [asyncio.create_task(get_key_ts_by_index_m3u8(title_and_id)) for title_and_id in
                    title_super_definition_href_list]
    await asyncio.wait(tasks_item_3)
    for task in tasks_item_3:
        ret = task.result()
        if not ret == -1:
            ts_list_and_name=ret
    #
    print(ts_list_and_name)
    tasks_item_4 = [asyncio.create_task(get_ts(ts,os.path.basename(ts))) for ts in
                    ts_list_and_name]
    await asyncio.wait(tasks_item_4)
    # # 用ffmpeg去合并ts为一个mp4文件

    tasks_item_5 = await ts_to_mp4_by_ffmpeg()


if __name__ == '__main__':
    start = time.time()
    asyncio.run(main())
    print(f"下载完毕,耗时：{time.time() - start}")
